
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import manager.mHost;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Administrator
 */
public final class mainForm extends javax.swing.JFrame {

   /**
    * Creates new form mainForm
    */
   private TreeModel tlThread;
   private static String currentDir;
   private List<mHost> lstHost;

   public mainForm() {
      this.setTitle("Tiện ích quản lý tiến trình từ xa");
      Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
      initComponents();
//      loadSetting();
      jProgressBar1.setValue(0);
//      getInformation();
      //Dịch chuyển về chính giữa
      this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2);
      jProgressBar1.setValue(100);
   }

   public void getInformation() {
      //Load nội dung sang tree
   }

   /**
    * @return the currentDir
    */
   public static String getCurrentDir() {
      //Lấy đường dẫn thực của ứng dụng
      if (currentDir == null || currentDir.equals("")) {
         Path currentRelativePath = Paths.get("");
         currentDir = currentRelativePath.toAbsolutePath().toString();
      }
      return currentDir;
   }

   private static String getValue(String tag, Element element) {//Lấy giá trị
      NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
      Node node = (Node) nodes.item(0);
      return node.getNodeValue().trim();
   }

   public void loadSetting() {
      //Lấy thông tin tiến trình từ host      
      //create the root node
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Danh sách máy chủ tiến trình");
      //create the child nodes
      try {
         //Lấy file XML cấu hình thông tin
         File manager = new File(getCurrentDir() + "/config/manager.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(manager);
         doc.getDocumentElement().normalize();
         //Chuẩn hóa
         NodeList nodes = doc.getElementsByTagName("thread");
         //Lấy thông tin port listener
         //Lấy thông tin Class ra và load lên
         System.out.println("+========================================================================================+");
         for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            mHost nodeThread = new mHost();
            if (node.getNodeType() == Node.ELEMENT_NODE) {
               Element element = (Element) node;
               System.out.println("+ Title: \t\t" + getValue("title", element));
               System.out.println("+ Ip: \t\t\t" + getValue("ip", element));
               System.out.println("+ Port: \t\t" + getValue("port", element));
               System.out.println("+ Timeout: \t\t" + getValue("timeout", element));
               nodeThread.setStrTitle(getValue("title", element));
               nodeThread.setStrIp(getValue("ip", element));
               nodeThread.setStrPort(getValue("port", element));
               nodeThread.setStrTimeout(getValue("timeout", element));
            }
            getLstHost().add(nodeThread);
         }
         System.out.println("+========================================================================================+");
      } catch (Exception ex) {
         Logger.getLogger(mainForm.class.getName()).log(Level.SEVERE, null, ex);
      }
      //Load lại vào tree
      for (int i = 0; i < getLstHost().size(); i++) {
         DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode(getLstHost().get(i).getStrTitle());
         vegetableNode.setUserObject(getLstHost().get(i));
         root.add(vegetableNode);
      }
      //create the tree by passing in the root node
      tlThread = new DefaultTreeModel(root);
      getInformation();
   }

   public List<String> makeCommand(String host, int port, String command) {
      //Hàm tạo kết nối và trả về danh sách các dòng nhận được
      List<String> rt = new ArrayList();
      try {
         Socket client = new Socket(host, port);
//         System.out.println("Just connected to " + client.getRemoteSocketAddress());
//         boolean meetExit = false;
         InputStream inputstream = System.in;
         InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
         BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

         OutputStream outputstream = client.getOutputStream();
         OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
         BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
//         while (!meetExit) {
         InputStream inputstreamSv = client.getInputStream();
         InputStreamReader inputstreamreaderSv = new InputStreamReader(inputstreamSv);
         BufferedReader bufferedreaderSv = new BufferedReader(inputstreamreaderSv);
         String string;
         String svStr;
//         System.out.print("\nCommand: ");
         if ((string = bufferedreader.readLine()).equals("exit")) {
//            meetExit = true;
         } else {
            bufferedwriter.write(string + '\n');
            bufferedwriter.flush();
//               System.out.println(">>: " + string);
            String revStr = "";
            while (!"".equals(svStr = bufferedreaderSv.readLine().trim()) && svStr != null && !svStr.equals("End")) {
//                  System.out.println(svStr);
//               revStr += svStr;
               rt.add(svStr);
            }

//               System.out.println("<<: " + revStr);
//         }
         }
         bufferedwriter.close();
         client.close();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         return rt;
      }
   }

   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
   // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
   private void initComponents() {

      jPanel3 = new javax.swing.JPanel();
      jScrollPane1 = new javax.swing.JScrollPane();
      tThread = new javax.swing.JTree();
      jPanel2 = new javax.swing.JPanel();
      jLabel1 = new javax.swing.JLabel();
      txtIP = new javax.swing.JTextField();
      jLabel2 = new javax.swing.JLabel();
      txtPort = new javax.swing.JTextField();
      jPanel1 = new javax.swing.JPanel();
      jButton1 = new javax.swing.JButton();
      jButton2 = new javax.swing.JButton();
      jButton3 = new javax.swing.JButton();
      jProgressBar1 = new javax.swing.JProgressBar();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setBackground(new java.awt.Color(255, 255, 255));

      jPanel3.setBackground(new java.awt.Color(255, 255, 255));

      tThread.setBorder(javax.swing.BorderFactory.createTitledBorder("Danh sách tiến trình"));
      tThread.setModel(getTlThread());
      tThread.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
         public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
            tThreadValueChanged(evt);
         }
      });
      jScrollPane1.setViewportView(tThread);

      jPanel2.setBackground(new java.awt.Color(255, 255, 255));
      jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Thông tin chi tiết"));

      jLabel1.setText("Địa chỉ:");

      txtIP.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtIPActionPerformed(evt);
         }
      });

      jLabel2.setText("Port:");

      txtPort.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtPortActionPerformed(evt);
         }
      });

      javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
      jPanel2.setLayout(jPanel2Layout);
      jPanel2Layout.setHorizontalGroup(
         jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(jPanel2Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(txtIP, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
      );
      jPanel2Layout.setVerticalGroup(
         jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(jPanel2Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(jLabel1)
               .addComponent(txtIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                  .addComponent(jLabel2)
                  .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );

      jPanel1.setBackground(new java.awt.Color(255, 255, 255));
      jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Điều khiển"));

      jButton1.setText("Start");
      jButton1.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
         }
      });

      jButton2.setText("Stop");
      jButton2.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
         }
      });

      jButton3.setText("Kill");
      jButton3.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
         }
      });

      javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
      jPanel1.setLayout(jPanel1Layout);
      jPanel1Layout.setHorizontalGroup(
         jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jButton1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
      );
      jPanel1Layout.setVerticalGroup(
         jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
         .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
         .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      );

      javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
      jPanel3.setLayout(jPanel3Layout);
      jPanel3Layout.setHorizontalGroup(
         jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
               .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
               .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
      );
      jPanel3Layout.setVerticalGroup(
         jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(jPanel3Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addGroup(jPanel3Layout.createSequentialGroup()
                  .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 500, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap())
      );

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      );

      pack();
   }// </editor-fold>//GEN-END:initComponents

   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
      // TODO add your handling code here:
      jProgressBar1.setValue(0);
//      repaint();
   }//GEN-LAST:event_jButton1ActionPerformed

   private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
      // TODO add your handling code here:
   }//GEN-LAST:event_jButton2ActionPerformed

   private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
      // TODO add your handling code here:
   }//GEN-LAST:event_jButton3ActionPerformed

   private void tThreadValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_tThreadValueChanged
      // TODO add your handling code here:
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) tThread.getLastSelectedPathComponent();
      /* if nothing is selected */
      if (node == null) {
         return;
      }
      try {
         /* retrieve the node that was selected */
         mHost nodeInfo = (mHost) node.getUserObject();
         txtIP.setText(nodeInfo.getStrIp());
         txtPort.setText(nodeInfo.getStrPort());
         node.add(new DefaultMutableTreeNode("1"));
         node.add(new DefaultMutableTreeNode("2"));
         node.add(new DefaultMutableTreeNode("3"));
      } catch (Exception ex) {
         System.out.println(ex);
      }
      /* React to the node selection. */
   }//GEN-LAST:event_tThreadValueChanged

   private void txtIPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIPActionPerformed
      // TODO add your handling code here:
   }//GEN-LAST:event_txtIPActionPerformed

   private void txtPortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPortActionPerformed
      // TODO add your handling code here:
   }//GEN-LAST:event_txtPortActionPerformed

   /**
    * @param args the command line arguments
    */
   public static void main(String args[]) {
      /* Set the Nimbus look and feel */
      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
       * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
       */
      try {
         for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Windows".equals(info.getName())) {
               javax.swing.UIManager.setLookAndFeel(info.getClassName());
               break;
            }
         }
      } catch (ClassNotFoundException ex) {
         java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
         java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
         java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (javax.swing.UnsupportedLookAndFeelException ex) {
         java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
      //</editor-fold>

      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable() {
         @Override
         public void run() {
            new mainForm().setVisible(true);
         }
      });
   }
   // Variables declaration - do not modify//GEN-BEGIN:variables
   private javax.swing.JButton jButton1;
   private javax.swing.JButton jButton2;
   private javax.swing.JButton jButton3;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JLabel jLabel2;
   private javax.swing.JPanel jPanel1;
   private javax.swing.JPanel jPanel2;
   private javax.swing.JPanel jPanel3;
   private javax.swing.JProgressBar jProgressBar1;
   private javax.swing.JScrollPane jScrollPane1;
   private javax.swing.JTree tThread;
   private javax.swing.JTextField txtIP;
   private javax.swing.JTextField txtPort;
   // End of variables declaration//GEN-END:variables

   public void loadFirstTree() {
   }

   /**
    * @return the tlThread
    */
   public TreeModel getTlThread() {
      if (tlThread == null) {
         loadSetting();
      }
      return tlThread;
   }

   /**
    * @param tlThread the tlThread to set
    */
   public void setTlThread(TreeModel tlThread) {
      this.tlThread = tlThread;
   }

   /**
    * @return the lstHost
    */
   public List<mHost> getLstHost() {
      if (lstHost == null) {
         lstHost = new ArrayList();
      }
      return lstHost;
   }

   /**
    * @param lstHost the lstHost to set
    */
   public void setLstHost(List<mHost> lstHost) {
      this.lstHost = lstHost;
   }
}
